Skip to main content

Classes

JavaScript does not have classes in the same sense as other object-oriented languages like Java or Python. ES6, however, did introduce a syntax for object creation that uses the class keyword.

  • It is basically a new syntax that does the exact same thing as the object constructors and prototypes we learned about in the constructor lesson.
  • The underlying mechanisms have not changed despite the different syntax (no classical inheritance going on).

I. Introduction to Classes​

1. Defining Classes​

Classes in JavaScript are special functions, so just as you can define function expressions and function declarations, a class can be defined in two ways: a class expression or a class declaration.

// Declaration
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

// Expression; the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

// Expression; the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

2. Property Getters and Setters​

There are two kinds of object properties.

  • The first kind is data properties. We already know how to work with them. All properties that we’ve been using until now were data properties.
  • The second type of property is something new. It’s an accessor property. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},

set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};

Example: From the outside, an accessor property looks like a regular property. We don’t call user.fullName as a function, we read it normally: the getter runs behind the scenes.

let user = {
name: "John",
surname: "Smith",

get fullName() {
return `${this.name} ${this.surname}`;
}
};

console.log(user.fullName); // John Smith

Attempting to assign user.fullName= will cause an error.

let user = {
get fullName() {
return `...`;
}
};

user.fullName = "Test"; // Error (property has only a getter)

To fix this, we can add a setter for user.fullName

let user = {
name: "John",
surname: "Smith",

get fullName() {
return `${this.name} ${this.surname}`;
},

set fullName(value) {
[this.name, this.surname] = value.split(" ");
}
};

// set fullName is executed with the given value.
user.fullName = "Alice Cooper";

console.log(user.name); // Alice
console.log(user.surname); // Cooper